package com.zyh;

import com.alibaba.fastjson2.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/homework")
public class HomeWork extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        String url = "jdbc:mysql://127.0.0.1:3306/stumanager";
        String username = "root";
        String password = "root";
        try (
                Connection connection = DriverManager.getConnection(url, username, password);
                Statement statement = connection.createStatement()
        ) {
            ResultSet resultSet = statement.executeQuery("select * from student");
            List<HomeStudent> list = new ArrayList<>();
            while (resultSet.next()) {
                list.add(new HomeStudent(resultSet.getInt("id"),
                        resultSet.getString("name"),
                        resultSet.getInt("sex"),
                        resultSet.getInt("age"),
                        resultSet.getString("phone")));
            }
            resp.setContentType("application/json;charset=utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().write(JSONObject.toJSONString(list));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
